package cn.wx.scholar.tool.interceptor;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import cn.wx.common.persistence.web.SpringContext;
import cn.wx.scholar.tool.jwt.JwtAuthFilter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Created by Scarlet on 2017/12/29.
 */
public class RequestInterceptor implements HandlerInterceptor{
	
	private static final Logger logger = LoggerFactory.getLogger("RequestLoggerInterceptor");
	
	private final AtomicLong id = new AtomicLong(0);
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		
		String rUrl = request.getRequestURI();
		
		logger.info("访问过来的URL：" + rUrl);
		/**
		 * 提取请求的日志
		 */
		Long requestId = id.getAndDecrement();
		request.setAttribute("requestId",requestId);
		request.setAttribute("request-time",System.currentTimeMillis());
		Map<String,Object> info = Maps.newHashMap();
		info.put("url",request.getRequestURL());
		Map<String,Object> header = Maps.newHashMap();
		Enumeration<String> headerNames =  request.getHeaderNames();
		if (headerNames!=null){
			while (headerNames.hasMoreElements()){
				String headerName = headerNames.nextElement();
				header.put(headerName,request.getHeader(headerName));
			}
		}
		info.put("method",request.getMethod());
		info.put("header",header);
		if ("GET".equalsIgnoreCase(request.getMethod())){
			info.put("queryParam",request.getQueryString());
		}else{
			info.put("queryParam", JSON.toJSONString(request.getParameterMap()));
		}
		
		Boolean credis = false;
		
		if("/sholar/ajax/query".equals(rUrl)){
			credis = true;
		}
		
		/**
		 * 验证token的合法性
		 */
		String token = request.getHeader("Authorization");
		JwtAuthFilter jwtAuthFilter = SpringContext.getBean(JwtAuthFilter.class);
		return jwtAuthFilter.filterInternal(response, token,credis);
		
	}
	
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

	}
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
	
	}
}
